package cn.caplike.demo.repository.bytebuddy;

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.matcher.ElementMatchers;

import java.io.File;
import java.io.IOException;

public class RedefiningAnExistingClass {

    public static void main(String[] args) throws IOException {
        ByteBuddyAgent.install();
        final DynamicType.Loaded<Foo> load = new ByteBuddy()
                .redefine(Foo.class)
                .method(ElementMatchers.named("sayHelloFoo")) // 根据名称来匹配需要拦截的方法
                .intercept(FixedValue.value("Hello Foo Redefined")) // 拦截方法调用，返回固定值
                .make() // 产生字节码
                .load(Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());

        Foo f = new Foo();
        System.err.println(f.sayHelloFoo());

        load.saveIn(new File(Foo.getClasspath())); // 覆盖源文件
    }

}
